<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <div class="query-card">
        <!-- <el-row type="flex" align="middle">
        <el-col :span="12">-->
        <div class="grid-content bg-purple search">
          <el-radio-group v-model="picktime" @change="changeDate">
            <el-radio-button label="1">今天</el-radio-button>
            <el-radio-button label="2">近半月</el-radio-button>
            <el-radio-button label="3">最近一个月</el-radio-button>
          </el-radio-group>
          <el-form ref="query" :model="query" label-width="100px">
            <el-form-item style="margin-bottom:0px" label="关键字">
              <i slot="label" class="el-icon-search" style="font-size:20px"></i>
              <el-input
                style="width:360px"
                v-model="query.keywords"
                placeholder="请输入手机号/商品名称/收货人姓名搜索"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px;" label="操作日期">
              <el-date-picker
                ref="picker"
                v-model="query.timeArr"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
            <!-- <el-form-item style="margin-bottom:0px" label="选择用户">
              <el-select
                v-model="userId"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="selectloading"
                style="width:260px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>-->
          </el-form>
        </div>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="queryAsk">查询</el-button>
          <el-button @click="queryReset">重置</el-button>
        </div>
        <!-- </el-col>
        </el-row>-->
      </div>
    </el-card>

    <!-- 表格 -->
    <el-card class="box-card" v-loading="loading">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部" name="0"></el-tab-pane>
        <el-tab-pane label="待发货" name="2"></el-tab-pane>
        <el-tab-pane label="待完善物流" name="3"></el-tab-pane>
        <el-tab-pane label="待收货" name="4"></el-tab-pane>
        <el-tab-pane label="已完成" name="5"></el-tab-pane>
      </el-tabs>
      <div class="head">
        <div style="width:20%">商品</div>
        <div style="width:20%">单价</div>
        <div style="width:20%">数量</div>
        <div>客户</div>
        <div>金额/积分</div>
        <div>地址</div>
        <div>支付类型</div>
        <div>订单状态</div>
        <!-- <div>操作</div> -->
      </div>
      <div class="order" v-for="item in tableData" :key="item.id+item.order_sn">
        <div class="order-title">
          <div>订单号：{{item.order_sn}}</div>
          <div style="margin-left:20px">支付时间：{{item.pay_time}}</div>
          <div style="margin-left:20px" v-if="item.pid==0">主订单</div>
          <div style="margin-left:20px" v-if="item.pid!=0">子订单</div>
        </div>
        <div class="order-list">
          <div class="goods">
            <div class="order-info" v-for="good in item.goods_info" :key="good.goods_info.img">
              <div>
                <el-avatar shape="square" :size="60" fit="fll" :src="good.goods_info.img"></el-avatar>
                <span style="margin-left:10px;width:70%">{{good.goods_info.goods_name}}</span>
              </div>
              <div style="padding-right: 10px;">￥{{good.price}}</div>
              <!-- <div style="padding-right: 10px;" v-if="good.is_integral==1">{{good.integral}}积分</div> -->
              <div style="padding-left: 13px;">x{{good.num}}</div>
            </div>
          </div>
          <!-- 用户信息 -->
          <div style="display:flex;flex-direction:column;width: 12.5%;text-align: center;">
            <el-button type="text" @click="handleEdite(item.user_id)">{{item.nickname}}</el-button>
            <span></span>
            <span>{{item.mobile}}</span>
          </div>
          <!-- 总金额 -->
          <div style="width: 12.5%;text-align: center;">￥{{item.totalPrice}}</div>
          <!-- <div
            style="width: 12.5%;text-align: center;"
            v-if="item.is_integral==1"
          >{{item.integral}}积分</div>-->
          <!-- 地址 -->
          <div style="width: 12.5%;padding-left: 5px;text-align: center;">
            <el-popover
              placement="top-start"
              title="详细地址"
              width="200"
              trigger="hover"
              :content="item.address_info.province+item.address_info.city+item.address_info.area+item.address_info.address"
            >
              <div
                slot="reference"
              >{{item.address_info.province+item.address_info.city+item.address_info.area}}</div>
            </el-popover>
          </div>
          <!-- 交易类型 -->
          <div style="width: 12.5%;padding-left: 12px;text-align: center;">
            <div v-if="item.pay_type==1">微信支付</div>
            <div v-if="item.pay_type==2">支付宝</div>
            <div v-if="item.pay_type==3">余额</div>
            <div v-if="item.pay_type==4">积分</div>
          </div>
          <!-- 订单状态 -->
          <div style="width: 12.5%;padding-left: 12px;text-align: center;">
            <el-tag type="success" v-if="item.status==5">已完成</el-tag>
            <el-tag type v-if="item.status==4">待收货</el-tag>
            <el-tag type="warning" v-if="item.status==3">待完善物流</el-tag>
            <el-tag type="danger" v-if="item.status==2">待发货</el-tag>
          </div>
          <!-- 操作 -->
          <!-- <div class="order-oprate">
            <el-button type="text" v-if="item.pid==0&&item.status==2" @click="goSplice(item)">去操作</el-button>
            <el-button
              type="text"
              v-if="item.pid!=0&&item.status==3"
              @click="goDelivery(item)"
            >去完善物流</el-button>
            <el-button type="text" @click="goDetail(item.id)">订单详情</el-button>
          </div>-->
        </div>
      </div>
      <div style="margin-top:20px;text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 拆分抽屉 -->
    <el-drawer
      :title="splicetitle"
      :visible.sync="splicedrawer"
      :direction="splicedirection"
      :before-close="splicehandleClose"
    >
      <el-form ref="spliceform" label-width="80px" style="margin-left:20px">
        <el-form-item label="收货人:">
          <div>{{splicedata.nickname}}</div>
        </el-form-item>
        <el-form-item label="联系电话:">
          <div>{{splicedata.mobile}}</div>
        </el-form-item>
        <el-form-item label="收货地址:">
          <div>{{spliceaddress}}</div>
        </el-form-item>
        <el-form-item label="即时配送:">
          <el-table
            ref="multipleTable"
            :data="splicedata.goods_info"
            tooltip-effect="dark"
            @selection-change="splicehandleSelectionChange"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="date" label="奖品封面" width="180">
              <template slot-scope="scope">
                <el-popover placement="top-start" title trigger="hover">
                  <img :src="scope.row.goods_info.img" alt style="max-width:250px" />
                  <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
                  <el-avatar
                    slot="reference"
                    shape="square"
                    :size="50"
                    fit="scale-down"
                    :src="scope.row.goods_info.img"
                  ></el-avatar>
                  <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
                  />-->
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="奖品名称" width="180">
              <template slot-scope="scope">
                <div>{{scope.row.goods_info.goods_name}}</div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="spec" label="商品规格"></el-table-column> -->
            <el-table-column label="金额">
              <template slot-scope="scope">
                <!-- <div v-if="scope.row.is_integral==1">积分{{scope.row.integral}}</div> -->
                <div>￥{{scope.row.goods_info.price}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量"></el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="运费:">
          <div>{{splicedata.freight}}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="spliceonSubmit">立即发货</el-button>
          <el-button @click="spliceSubCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 发货抽屉 -->
    <el-drawer
      :title="delivertitle"
      :visible.sync="deliverdrawer"
      :direction="deliverdirection"
      :before-close="deliverhandleClose"
    >
      <el-form ref="deliverform" label-width="80px" style="margin-left:20px">
        <el-form-item label="收货人:">
          <div>{{deliverdata.nickname}}</div>
        </el-form-item>
        <el-form-item label="联系电话:">
          <div>{{deliverdata.mobile}}</div>
        </el-form-item>
        <el-form-item label="收货地址:">
          <div>{{deliveraddress}}</div>
        </el-form-item>
        <el-form-item label="奖品信息:">
          <el-table
            ref="multipleTable"
            :data="deliverdata.goods_info"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column align="center" prop="date" label="奖品封面" width="100">
              <template slot-scope="scope">
                <el-popover placement="top-start" title trigger="hover">
                  <img :src="scope.row.goods_info.img" alt style="max-width:250px" />
                  <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
                  <el-avatar
                    slot="reference"
                    shape="square"
                    :size="50"
                    fit="scale-down"
                    :src="scope.row.goods_info.img"
                  ></el-avatar>
                  <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
                  />-->
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" label="奖品名称">
              <template slot-scope="scope">
                <div>{{scope.row.goods_info.goods_name}}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="num" label="数量" width="80"></el-table-column>
            <el-table-column align="center" prop="num" label="快递公司">
              <template slot-scope="scope">
                <el-select style="width:100%" v-model="scope.row.express_id" placeholder="请选择快递公司">
                  <el-option
                    v-for="item in deliverOptions"
                    :key="item.kd_sn"
                    :label="item.name"
                    :value="item.kd_sn"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="num" label="快递单号">
              <template slot-scope="scope">
                <el-input
                  @input="snToCompany(scope.row)"
                  v-model="scope.row.express_sn"
                  placeholder="请输入快递单号"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="运费:">
          <div>{{deliverdata.freight}}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="deliveronSubmit">立即发货</el-button>
          <el-button @click="deliverSubCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  invoiceList,
  getDeliveryCompony,
  delivery,
  spliceInvoice
} from "@/api/invoice";
import { snToCompany } from "@/api/commodity";
import { consumerList } from "@/api/consumer";
import { parseTime } from "@/utils/index";

export default {
  name: "Invoice",
  props: {
    user_id: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //query
      query: {
        keywords: "",
        add_time: "",
        status: "",
        timeArr: []
      },
      options: "",
      selectloading: false,
      userId: "",
      tableData: [],
      activeName: "0",
      loading: false,
      picktime: "1",
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", [new Date(), new Date()]);
            }
          },
          {
            text: "近半月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      // 拆分抽屉
      splicedrawer: false,
      splicedirection: "rtl",
      splicetitle: "拆分订单",
      splicedata: [],
      spliceaddress: "",
      spliceform: {
        id: "",
        idArr: [],
        type: 1
      },
      // 发货抽屉
      deliverdrawer: false,
      deliverdirection: "rtl",
      delivertitle: "发货",
      deliverdata: [],
      deliveraddress: "",
      deliverform: {
        id: "",
        express_data: []
      },
      deliverOptions: ""
    };
  },
  mounted() {
    this.query.timeArr = [new Date(), new Date()];
    // this.getList();
    this.getCopmany();
  },
  methods: {
    // 获取列表
    async getList() {
      this.loading = true;
      this.query.add_time =
        parseTime(this.query.timeArr[0], "{y}-{m}-{d}") +
        "," +
        parseTime(this.query.timeArr[1], "{y}-{m}-{d}");
      const res = await invoiceList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.keywords,
        status: this.activeName,
        add_time: this.query.add_time,
        user_id: this.user_id
      });
      console.log(res);
      this.loading = false;
      this.total = res.count;
      this.tableData = res.data;
      this.tableData.forEach(item => {
        item.pay_time = parseTime(item.pay_time, "{y}-{m}-{d} {h}:{i}:{s}");
      });
    },
    changeDate() {
      console.log(this.picktime);
      if (this.picktime == 1) {
        this.$set(this.query, "timeArr", [new Date(), new Date()]);
        this.getList();
      } else if (this.picktime == 2) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
        this.$set(this.query, "timeArr", [start, end]);
        this.getList();
      } else if (this.picktime == 3) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        this.$set(this.query, "timeArr", [start, end]);
        this.getList();
      }
    },
    // 搜索选择
    // async remoteMethod(query) {
    //   if (query !== "") {
    //     this.selectloading = true;
    //     const res = await consumerList({
    //       page: "1",
    //       limit: "10",
    //       keywords: query
    //     });
    //     console.log(res);
    //     this.options = res.data;
    //     this.selectloading = false;
    //   } else {
    //     this.options = [];
    //   }
    // },
    queryAsk() {
      console.log(this.query);
      this.currentPage = 1;
      this.getList();
    },
    queryReset() {
      this.total = 0;
      this.currentPage = 1;
      this.pageSize = 10;
      this.query.add_time = "";
      this.query.keywords = "";
      this.query.status = "";
      this.userId = "";
      this.picktime = 1;
      this.query.timeArr = [new Date(), new Date()];
      this.getList();
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current;
      this.getList();
    },
    async handleClick(tab, event) {
      //   console.log(tab, event);
      await this.getList();
      this.activeName = tab.name;
    },
    // 跳转用户
    handleEdite(id) {
      this.$router.push({
        path: "/consumer/consumeroprate",
        query: { id: id }
      });
    },
    // 详情
    goDetail(id) {
      this.$router.push({
        name: "InvoiceDetail",
        query: { id }
      });
    },
    // 拆分订单
    goSplice(item) {
      this.splicedrawer = true;
      console.log(item);
      this.spliceform.id = item.id;
      this.splicedata = item;
      this.spliceaddress = item.address_info.address;
    },
    splicehandleClose(done) {
      this.splicedrawer = false;
      done();
    },
    spliceSubCancel() {
      this.splicedrawer = false;
    },
    splicehandleSelectionChange(val) {
      console.log(val);
      this.spliceform.idArr = [];
      val.forEach(item => {
        this.spliceform.idArr.push(item.id);
      });
    },
    async spliceonSubmit() {
      if (!this.spliceform.idArr) {
        this.$message.error("请选择拆分商品");
        return;
      }
      const res = await spliceInvoice({ ...this.spliceform });
      if (res.st == 1) {
        this.$message({
          message: "拆分成功",
          type: "success"
        });
        this.splicedrawer = false;
        this.getList();
      } else {
        this.$message.error("拆分失败");
        console.log(res);
      }
    },
    // 发货
    goDelivery(item) {
      console.log(item);
      this.deliverdrawer = true;
      // this.form.id = id;
      // this.form.order = order;
      this.deliverform.id = item.id;
      this.deliverdata = item;
      this.deliveraddress = item.address_info.address;
    },
    deliverhandleClose(done) {
      this.deliverdrawer = false;
      done();
    },
    deliverSubCancel() {
      this.deliverdrawer = false;
    },
    // 获取快递公司
    async getCopmany() {
      const res = await getDeliveryCompony();
      console.log(res);
      this.deliverOptions = res.data;
    },
    // 根据单号获取公司
    async snToCompany(row) {
      console.log(row.express_sn);
      const res = await snToCompany({ express_sn: row.express_sn });
      console.log(res);
      this.deliverdata.goods_info.forEach(item => {
        if (res.data && res.data.length > 0) {
          if (item.id == row.id) {
            for (let i = 0; i < res.data.length; i++) {
              if (res.data[i].comCode == "zhongtong") {
                this.$set(item, "express_id", res.data[i].comCode);
              } else if (res.data[i].comCode == "shunfeng") {
                this.$set(item, "express_id", res.data[i].comCode);
              } else if (res.data[i].comCode == "jd") {
                this.$set(item, "express_id", res.data[i].comCode);
              }
            }
          }
        } else {
          this.$set(item, "express_id", "other");
        }
      });
    },
    async deliveronSubmit() {
      console.log(this.deliverdata.goods_info);
      this.deliverform.express_data = [];
      for (let i = 0; i < this.deliverdata.goods_info.length; i++) {
        if (
          !this.deliverdata.goods_info[i].express_id ||
          !this.deliverdata.goods_info[i].express_sn
        ) {
          this.$message.error("请填写所有商品的物流");
          return;
        }
        //筛选出快递公司id
        let id = "";
        this.deliverOptions.forEach(item => {
          if (item.kd_sn == this.deliverdata.goods_info[i].express_id) {
            id = item.id;
          }
        });
        const dt = {
          id: this.deliverdata.goods_info[i].id,
          express_id: id,
          express_sn: this.deliverdata.goods_info[i].express_sn
        };
        this.deliverform.express_data.push(dt);
      }

      const res = await delivery(this.deliverform);
      if (res.st == 1) {
        this.$message({
          message: "发货成功",
          type: "success"
        });
        this.deliverdrawer = false;
        this.getList();
      } else {
        this.$message.error("发货失败");
        console.log(res);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  // ::v-deep .el-input--medium .el-input__inner {
  //   width: 360px;
  // }
  .box-card {
    margin-bottom: 20px;
  }
  .search {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}
.query-card {
  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;
  }
}

::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  width: 1000px !important;
  overflow: auto;
}
//订单列表
.head {
  display: flex;
  width: 100%;
  border-bottom: 1px solid #d4d4d4;
  line-height: 40px;
  div {
    width: 12.5%;
    text-align: center;
  }
}
.order {
  width: 100%;
  margin-top: 15px;
  .order-title {
    display: flex;
    width: 100%;
    background-color: #e8ecf1;
    padding: 0 10px;
    line-height: 40px;
    font-size: 14px;
  }
  .order-list {
    width: 100%;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #d4d4d4;
    .goods {
      width: 60%;
      display: flex;
      flex-direction: column;
      .order-info {
        display: flex;
        width: 100%;
        height: 80px;
        padding: 10px;
        border-top: 1px solid #d4d4d4;
        &:first-child {
          border: none;
        }
        div {
          width: 33.3%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
        }
      }
    }
    .order-oprate {
      display: flex;
      flex-direction: column;
      width: 12.5%;
      ::v-deep .el-button + .el-button {
        margin: 0;
      }
    }
  }
}
</style>